package com.eqxiu.ieditor.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.NamedThreadLocal;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Component
public class ApiStatInterceptor implements HandlerInterceptor {

    // @Autowired(required = false)
    // @Qualifier("pageStatCache")
    // private StringRedisTemplate redisTemplate;

    private static final Logger logger = LoggerFactory.getLogger(ApiStatInterceptor.class);

    private NamedThreadLocal<Long> startTimeThreadLocal = new NamedThreadLocal<Long>("StopWatch-ApiStat");

    private static final int timeout = 1000;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        long beginTime = System.currentTimeMillis();
        startTimeThreadLocal.set(beginTime);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {
        long endTime = System.currentTimeMillis();
        Long beginTime = startTimeThreadLocal.get();
        long consumeTime = endTime - beginTime;
        if (consumeTime > timeout) {
            logger.warn("uri: {} , consume time : {}", request.getRequestURI(), consumeTime);
            // redisTemplate.opsForZSet().add("status:url",request.getRequestURI(),consumeTime);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {

    }

}
